import { defineStore } from 'pinia';

export const useCartStore = defineStore('cart', {
  state: () => ({
    cartItems: [],
    selectedItems: [] 
  }),
  actions: {
    addToCart(product) {
      const existingItem = this.cartItems.find(item => item.id === product.id);
      
      if (existingItem) {
        existingItem.quantity += product.quantity || 1;
      } else {
        this.cartItems.push({
          ...product,
          quantity: product.quantity || 1
        });
      }
    },
    removeItem(productId) {
      this.cartItems = this.cartItems.filter(item => item.id !== productId);
    },
    clearCart() {
      this.cartItems.length = 0;
    },
    totalItems() {
      return this.cartItems.reduce((total, item) => total + item.quantity, 0);
    },
    totalPrice() {
      return this.cartItems.reduce((total, item) => {
        const price = item.discount 
          ? item.price * (1 - item.discount / 100)
          : item.price;
        return total + (price * item.quantity);
      }, 0);
    },
    // 新增方法：切换选中状态
    toggleItemSelection(productId) {
      const index = this.selectedItems.indexOf(productId);
      if (index === -1) {
        this.selectedItems.push(productId);
      } else {
        this.selectedItems.splice(index, 1);
      }
    },
    // 修改后的计算方法：只计算选中商品
    selectedTotalItems() {
      return this.cartItems
        .filter(item => this.selectedItems.includes(item.id))
        .reduce((total, item) => total + item.quantity, 0);
    },
    selectedTotalPrice() {
      return this.cartItems
        .filter(item => this.selectedItems.includes(item.id))
        .reduce((total, item) => {
          const price = item.discount 
            ? item.price * (1 - item.discount / 100)
            : item.price;
          return total + (price * item.quantity);
        }, 0);
    },
    // 清空选中状态
    clearSelection() {
      this.selectedItems = [];
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'cart',
        storage: localStorage,
        paths: ['cartItems', 'selectedItems']
      }
    ]
  }
});